package zack.middleware.hystrix;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import zack.middleware.hystrix.annotation.DoHystrix;
import zack.middleware.hystrix.valve.impl.HystrixValveImpl;

import java.lang.reflect.Method;

/**
 * @author A1793
 */
@Aspect
@Component
public class DoHystrixPoint {

    //捕获织入点
    @Pointcut("@annotation(zack.middleware.hystrix.annotation.DoHystrix)")
    public void aopPoint(){
    }
    //对注解了DoHystrix的方法进行增强并将原方法的注解信息赋值给doGovern
    @Around("aopPoint() && @annotation(doGovern)")
    public Object doRouter(ProceedingJoinPoint joinPoint, DoHystrix doGovern) throws Throwable {
        HystrixValveImpl hystrixService = new HystrixValveImpl(doGovern);
        return hystrixService.access(joinPoint,getMethod(joinPoint), joinPoint.getArgs());
    }
    private Method getMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        return joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
    }
}
